package com.fenquen.dfs.base.utils;

import java.util.regex.Pattern;

public class BiUtils {
    public static int getUByte(byte data) {
        return data & 0xFF;
    }

    public static int getUShort(short data) {
        return data & 0xFFFF;
    }

    public static long getUInt(int data) {
        return data & 0xFFFFFFFFL;
    }

    /**
     * 字节数组转化为IP
     *
     * @param bytes
     * @return int
     */
    public static String bytes2Ip(byte[] bytes) {
        if (bytes.length != 4) {
            throw new RuntimeException("要解析的byte数组必须是4个字节");
        }

        return String.valueOf(bytes[0] & 0xFF) +
                '.' +
                (bytes[1] & 0xFF) +
                '.' +
                (bytes[2] & 0xFF) +
                '.' +
                (bytes[3] & 0xFF);
    }

    private static final Pattern IP_REG_EXP = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");

    public static byte[] ip2ByteArr(String ip) {
        if (IP_REG_EXP.matcher(ip).matches() == false) {
            throw new RuntimeException("ip地址不符合规则");
        }

        String[] ipComponents = ip.split("\\.");
        byte[] result = new byte[4];
        int a = 0;
        for (String component : ipComponents) {
            result[a++] = (byte) (Integer.parseInt(component));
        }

        return result;
    }

    public static String byteArr2HexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder(bytes.length);
        for (byte b : bytes) {
            String a = Integer.toHexString(BiUtils.getUByte(b));
            if (a.length() == 1) {
                a = "0" + a;
            }
            stringBuilder.append(a);
        }
        return stringBuilder.toString();
    }
}
